package com.my.mygaode

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.text.TextUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition

object GlideUtils {
    /**
     * 回调bitmap
     * @param context Context?
     * @param url String?
     * @param fillet Float
     * @param callBack Function1<Bitmap, Unit>
     */
    fun getImageUrlToBitmap(
        context: Context?,
        url: String?,
        callBack: (Bitmap) -> Unit
    ) {
        if (context == null) return
        Glide.with(context)
            .asBitmap()
            .load(url)
            .apply(getNomalOptions())
            .into(object : SimpleTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    callBack(resource)
                }
            })
    }


    /**
     * 宽高比取最大值缩放图片.
     *
     * @param bitmap     加载的图片
     * @param widthSize  缩放之后的图片宽度,一般就是屏幕的宽度.
     * @param heightSize 缩放之后的图片高度,一般就是屏幕的高度.
     */
    fun getScaleToBitmap(bitmap: Bitmap?, widthSize: Int, heightSize: Int): Bitmap? {
        if (bitmap == null || bitmap.isRecycled) return null
        val bmpW = bitmap.width
        val bmpH = bitmap.height
        val scaleW = widthSize.toFloat() / bmpW
        val scaleH = heightSize.toFloat() / bmpH
        //取宽高最大比例来缩放图片
        val max = Math.max(scaleW, scaleH)
        val matrix = Matrix()
        matrix.postScale(max, max)
        return Bitmap.createBitmap(bitmap, 0, 0, bmpW, bmpH, matrix, true)
    }

    /**
     * 异步线程处理，下载图片文件逻辑(最好原图下载,然后用bitmap工具压缩到指定图片位置)
     * @param context Context
     * @param path String
     * @param width Int
     * @param height Int
     * @param isCircle Boolean 是否将bitmap处理成圆形
     * @return Bitmap?
     */
    fun getImageBitmap(
        context: Context,
        path: String?,
        width: Int = 0,
        height: Int = 0,
        isCircle: Boolean = false
    ): Bitmap? {
        if (TextUtils.isEmpty(path)) return null
        var w = if (width <= 0) Target.SIZE_ORIGINAL else width
        var h = if (height <= 0) Target.SIZE_ORIGINAL else height
        val requestBuilder =
            Glide.with(context).asBitmap().load(path)
        if (isCircle) {
            requestBuilder.optionalCircleCrop()
        }
        return requestBuilder.apply(
            getNomalOptions()
        ).submit(w, h).get()
    }

    fun getNomalOptions(): RequestOptions {
        return RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)!!
    }
}